package org.demo.system.controller;

import org.demo.base.auth.domain.SysUser;
import org.demo.base.file.domain.SysFile;
import org.demo.base.file.service.FileService;
import org.demo.base.mvc.HttpResult;
import org.demo.base.util.LoginHelper;
import org.demo.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 用户的增删改查啊
 * 注册和登录，不在这里
 * @author tomdog
 */
@RestController
public class UserController {

    @Autowired
    private FileService fileService;
    @Autowired
    private UserService userService;

    /**
     * 修改当前用户的头像
     */
    @PostMapping("/avatar")
    public HttpResult login(MultipartFile file) {
        // 上传头像
        SysFile upload = fileService.upload(file, "头像");
        // 当前用户的头像路径改
        SysUser sysUser = LoginHelper.currentLoginUser();
        userService.updateAvatar(
                upload.getPath(), sysUser.getId()
        );
        // 更新session中的用户
        sysUser.setAvatar(upload.getPath());
        LoginHelper.saveSession(sysUser);
        return HttpResult.success();
    }

    /**
     * 修改用户
     */
    @PutMapping("/user")
    public HttpResult updateUser(@RequestBody SysUser user) {
        if(user.getId()==null) {
            throw new RuntimeException("必须指定要修改的用户id");
        }
        userService.updateUser(user);
        return HttpResult.success();
    }

    /**
     * 批量添加用户
     */
    @PostMapping("/users")
    public HttpResult addUsers(@RequestBody List<SysUser> users) {
        userService.addUsers(users);
        return HttpResult.success();
    }
}
